//相关公共方法

class Event {

    constructor() {
        this._eventHandler = {};
    }

    trigger() {
        //将参数转换为数组
        var arg = Array.prototype.slice.apply(arguments, [0]);
        //取第一个，并从数组中删除，事件key
        var type = arg.shift();
        if (type) {
            type = type.toLowerCase();
        }
        if (!this._eventHandler || !this._eventHandler[type]) {
            return false;
        }
        var handlers = this._eventHandler[type];
        handlers.forEach(function (handler) {
            handler.cb.apply(handler.domain || this, arg);
        });
        return true;
    }
    on(type, callback, domain) {
        if (!this._eventHandler[type]) {
            this._eventHandler[type] = [];
        }
        this._eventHandler[type].push({
            cb: callback,
            domain: domain
        });
        return true;
    }
    off(type, callback, domain) {
        var handlers = this._eventHandler[type];
        if (handlers && handlers.length > 0) {
            var len = handlers.length;
            var handler;
            for (var i = 0; i < len; i++) {
                handler = handlers[i];
                if (handler && callback === handler.cb) {
                    if (domain && domain !== handler.domain) {
                        continue;
                    }
                    handlers.splice(i, 1);
                    i--;
                    len--;
                }
            }
        }
        if (handlers && handlers.length === 0) {
            delete this._eventHandler[type];
        }
    }
}

export default Event